package org.helgoboss.janana_tray_ref_impl;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;

import java.awt.AWTException;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.Toolkit;
import java.awt.Image;
import java.net.URL;

import org.helgoboss.janana_tray.JananaTray;
import org.helgoboss.janana_tray.JananaTrayAddOn;
import org.helgoboss.janana_artwork.JananaLogo;

public class JananaTrayRefImpl implements JananaTray, BundleActivator {
    private static BundleContext bundleContext;
    
    private ServiceTracker addOnTracker;
    private TrayIcon icon;
    
    public TrayIcon getIcon() {
        return icon;
    }
    
    private void createIcon() {
        Image image = JananaLogo.small();
        icon = new TrayIcon(image, "", new PopupMenu());
        icon.setImageAutoSize(true);
        try {
			SystemTray.getSystemTray().add(icon);
		} catch (AWTException e) {
			throw new RuntimeException(e);
		}
    }
	
	public void start(BundleContext context) throws Exception {
		bundleContext = context;
		if (SystemTray.isSupported()) {
			createIcon();
			context.registerService(JananaTray.class.getName(), this, null);
			
			/* Watch add-ons */
			addOnTracker = new ServiceTracker(context, JananaTrayAddOn.class.getName(), null) {
	        	@Override
	        	public Object addingService(ServiceReference reference) {
	        		JananaTrayAddOn addOn = (JananaTrayAddOn) context.getService(reference);
	        		addOn.addToJananaTray(JananaTrayRefImpl.this);
	        		return addOn;
	        	}
	        	
	        	/**
	        	 * {@inheritDoc}
	        	 */
	        	@Override
	        	public void removedService(ServiceReference reference, Object service) {
	        		JananaTrayAddOn addOn = (JananaTrayAddOn) context.getService(reference);
	        		addOn.removeFromJananaTray(JananaTrayRefImpl.this);
	        		context.ungetService(reference);
	        	}
	        };
	        addOnTracker.open();
		}
	}

	public void stop(BundleContext context) throws Exception {
		if (SystemTray.isSupported()) {
            Object[] objects = addOnTracker.getServices();
            if (objects != null) {
                for (Object obj: objects) {
                    JananaTrayAddOn addOn = (JananaTrayAddOn) obj;
                    addOn.removeFromJananaTray(this);
                }
            }
            addOnTracker.close();
			SystemTray.getSystemTray().remove(icon);
			icon.getImage().flush();
			icon = null;
		}
		bundleContext = null;
	}
    
    
}
